from django.core.paginator import Paginator, EmptyPage
from rest_framework import status
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from goods.models import SKU
from decimal import Decimal

from utils.pagination import StandardResultsSetPagination
from .serializers import *
from rest_framework.response import Response


class GoodsUnComment(GenericAPIView):

    permission_classes = [IsAuthenticated]

    def get(self,request,order_id):
        order_goods = OrderGoods.objects.filter(order_id=order_id,is_commented=False)
        serializer = GoodsSerializer(instance=order_goods,many=True)
        data = serializer.data
        # for good in order_goods:
        #     data['sku']['id'] = good.sku_id
        for sku_obj in data:
            sku_obj['id'] = sku_obj['sku']['id']
        return Response(serializer.data)

class CommentAPIView(GenericAPIView):
    permission_classes = [IsAuthenticated]

    # def post(self, request, order_id):
    #     data = request.data
    #     sku = OrderGoods.objects.filter(sku=data.get('sku'),order_id=data.get('order'),is_commented=False).first()
    #     sku.comment = request.data['comment']
    #     sku.is_commented = True
    #     sku.score = request.data['score']
    #     sku.is_anonymous = request.data['is_anonymous']
    #     sku.save()
    #     skus = OrderGoods.objects.filter(order_id=data.get('order'),is_commented=False).count()
    #     print(skus)
    #     if skus == 0:
    #         order = OrderInfo.objects.get(order_id=data.get('order'))
    #         order.status = 2
    #         order.save()
    #     serializer = CommentSerializers(instance=sku)
    #
    #     return Response(serializer.data)

    def post(self, request, order_id):
        data = request.data
        sku_id = data.get('sku')
        ordergoods = OrderGoods.objects.filter(order_id=order_id, sku=sku_id).first()
        serializer = Comment_ListSerializers(instance=ordergoods, data=data, context={'pk': order_id})
        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            print(e)
        serializer.save()
        return Response(serializer.data)


class OrderSettlementView(APIView):
    """
    订单结算
    """
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        """
        获取
        """
        user = request.user

        # 从购物车中获取用户勾选要结算的商品信息
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)

        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(redis_cart[sku_id])

        # 查询商品信息
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]

        # 运费
        freight = Decimal('10.00')

        serializer = OrderSettlementSerializer({'freight': freight, 'skus': skus})
        return Response(serializer.data)


class OrdersView(GenericAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = OrderCommitSerializer
    pagination_class = StandardResultsSetPagination

    def post(self, request):
        """
        订单数据保存:
        1. 获取参数并进行校验(参数完整性，address是否存在，pay_method是否合法)
        2. 保存订单的数据
        3. 返回应答，订单创建成功
        """
        # 1. 获取参数并进行校验(参数完整性，address是否存在，pay_method是否合法)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 2. 保存订单的数据(create)
        serializer.save()

        # 3. 返回应答，订单创建成功
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def get(self, request):

        # 获取用户
        user = request.user
        pagination = request.query_params
        page = int(pagination['page'])
        page_size = int(pagination['page_size'])
        # 获取订单
        orders = OrderInfo.objects.filter(user_id=user.id).all().order_by('-create_time')
        count = len(orders)
        orders = orders[(page - 1) * page_size: page * page_size]
        order_ids = [order.order_id for order in orders]
        results = []  # orders

        for order_id in order_ids:
            the_order = {}
            skus = []
            order = OrderInfo.objects.get(order_id=order_id)
            the_order['create_time'] = str(order.create_time)[:19]
            the_order['order_id'] = order.order_id
            the_order['total_amount'] = order.total_amount+order.freight
            the_order['freight'] = order.freight
            the_order['pay_method'] = order.pay_method
            the_order['status'] = order.status
            the_order['skus'] = []
            sku_list = order.ordergoods_set.all()
            for sku_obj in sku_list:
                skus = {}
                skus['price'] = sku_obj.price
                skus['count'] = sku_obj.count
                skus['sku'] = {}
                skus['sku']['default_image_url'] = sku_obj.sku.default_image_url
                skus['sku']['name'] = sku_obj.sku.name
                the_order['skus'].append(skus)
            results.append(the_order)
        data = {
            'count': count,
            'results': results
        }
        # return pg.get_paginated_response(data)
        return Response(data)
